package com.ebt.dl.service;

import java.math.BigInteger;
import java.security.SecureRandom;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.ebt.dl.domain.User;

@Service
public class TokenService {

	private static Map<String, String> tokenMap = new HashMap<>();

	@Autowired
	private UserService userService;

	public String authenticateUser(String userId, String password) throws Exception {
		authenticate(userId, password);
		String token = issueToken(userId);
		return token;
	}

	public String validateToken(String token) {
		String userId = tokenMap.get(token);
		if (userId == null) {
			return null;
		}
		return userId;
	}

	private void authenticate(String userId, String password) throws Exception {
		// Authenticate against a database, LDAP, file or whatever
		// Throw an Exception if the credentials are invalid
		User user = userService.getUserByUserId(userId);
		if (!password.equals(user.getPassword())) {
			throw new Exception();
		}

	}

	private String issueToken(String userId) {
		// Issue a token (can be a random String persisted to a database or a
		// JWT token)
		// The issued token must be associated to a user
		// Return the issued token

		Random random = new SecureRandom();
		String token = new BigInteger(130, random).toString(32);
		tokenMap.put(token, userId);
		return token;
	}
}
